import sys
sys.path.append("..")  # 也可以这样

from utils.cloud_utils import notify_cloud_v2
from config import similarity_threshold
from celery import chain, group
from celerytask import app
from celery import chord
from utils.video_utils import synthesize_video
from tybase.tools.image_utils import delete_file_or_directory
from tybase.tools.image_utils import url_to_md5
from utils.cloud_utils import upload_file_to_aliyun, transform_path, upload_file_to_qiniu
from loguru import logger
from utils.video_utils import split_video_into_frames, 加水印
from config import kSourceVideosFrame, kUserSwapperFaceFrames, kFontPath
import time
import os
from datetime import datetime
from uuid import uuid4


# 人脸验证的api流程
preprocess_source_images_v2 = app.tasks['celerytask.tasks.preprocess_source_images_v2']
process_workflow_V3 = app.tasks['celerytask.tasks.start_V3']

# 视频分割
async_split_video_into_frames = app.tasks["workflows.workflows_base.async_split_video_into_frames"]
post_process_task = app.tasks["workflows.workflows_base.post_process_task"]
process_images_many_face_task = app.tasks["workflows.workflows_base.process_images_many_face_task"]
callback = app.tasks["workflows.workflows_base.callback"]


def 多人_视频_换脸(requests_data):
    try:
        # 数据的基础准备
        帧数 = requests_data.get("frames", 15)  # 如果没有就15帧
        水印 = requests_data.get("shuiyin", True)  # 如果没有就15帧
        oss_name = requests_data.get("oss_name", "ali")  # 如果没有就15帧
        # 生成一个唯一的任务 ID
        unique_task_id = str(uuid4())
        # 记录开始时间
        start_time = datetime.now()
        # 这里要进行拆分来处理!
        frame_name = "frame_%04d.jpg"

        # 先并行分析人脸向量与把视频进行分割
        parallel_tasks = group([
            # 第一.0步: 视频分割
            async_split_video_into_frames.s(
                video_url=requests_data["target_video"], frame_rate=帧数, frame_name=frame_name, save_path=kSourceVideosFrame,task_id = unique_task_id),
            # 第一.1步: 解析人脸
            preprocess_source_images_v2.si(requests_data["face_data"],unique_task_id)
        ])

        # 使用 chord 组织任务流
        result = chord(parallel_tasks)(callback.s(
            requests_data, 帧数, frame_name, 水印, oss_name,unique_task_id))
        # 开始执行任务流
        return {"task_id":unique_task_id,"task_id_": result.id}

    except Exception as e:
        logger.error(f"任务链执行失败: {e}")
        return {}


if __name__ == '__main__':
    from tybase.tools.Task import TaskRunner
    # 可以把参数全部包装在这里,也比较简单!
    requests_data = {
        "target_video": "https://ty-aihuanlian.oss-cn-shanghai.aliyuncs.com/test/RPReplay_Final1699878287.mov",
        "face_data": [
            {
                "target_face_url": "http://ty-huanlian.oss-cn-shanghai.aliyuncs.com/swap_face%2F202311%2Fbest_face_0_1700020151_output_frame_4.jpg",
                "user_face_urls": ["http://oss.ubookapp.com/outputs/test/WX20231115-121354@2x.png"]
            },
            {
                "target_face_url": "http://ty-huanlian.oss-cn-shanghai.aliyuncs.com/swap_face%2F202311%2Fbest_face_1_1700020151_output_frame_6.jpg",
                "user_face_urls": ["https://ty-aihuanlian.oss-cn-shanghai.aliyuncs.com/test/IMG_2760.jpg"]
            }

        ],
        "帧数": 15,
        "水印": True,
        "oss_name": "ali"
    }

    # 最终传递的
    print(多人_视频_换脸(requests_data))
    # 创建后台任务
    # task = TaskRunner.Task(视频_换脸, {'param1': 'value1', 'param2': 'value2'}, callback=notify)
